import json
from datetime import datetime, timedelta
from rest_framework.views import APIView
from rest_framework.response import Response
from schedule import models
from host.models import Host
from django_celery_beat.models import PeriodicTask, IntervalSchedule


# 获取周期类型数据返回给客户端
class PeriodView(APIView):
    def get(self,request):
        data = models.TaskSchedule.period_way_choices
        return Response({'period_way_choices': data})


class TaskView(APIView):
    def get(self,request):
        # 1. 获取任务列表数据返回给客户端
        # 2. 去redis中获取每个任务的执行结果展示给客户端
        pass

    def post(self,request):
        # {'task_name': 'kkk', 'hosts': [10], 'period_way': '2', 'task_cmd': 'ls', 'period_content': '12'}
        period_way = request.data.get('period_way')
        hosts_ids = request.data.get('hosts')
        task_cmd = request.data.get('task_cmd')  # 要执行的任务指令
        period_content = request.data.get('period_content')
        task_name = request.data.get('task_name') # 任务名称，注意不能重复

        if period_way == '1':  # 普通周期任务,默认单位为秒数，可以选择修改
            schedule, created = IntervalSchedule.objects.get_or_create(
                every=int(period_content),
                period=IntervalSchedule.SECONDS,
            )
            period_obj = PeriodicTask.objects.create(
                interval=schedule,  # 上面创建的时间周期对象
                name=task_name,
                # task='celery_tasks.tasks.schedule_task',
                task='schedule_task',  # name of task.
                # task='my_task2',  # name of task.
                args=json.dumps([task_cmd, hosts_ids]),
                expires=datetime.utcnow() + timedelta(seconds=30)
            )
            period_beat = period_obj.id  # 任务的ID,用于保存到我们自己的定时任务数据表,方便之后暂停或删除定时任务
        elif period_way == '2':   # 一次性任务
            period_beat = 1
            pass
        else:  # cron任务
            period_beat = 1
            pass

        # 应该加事务, 关系到了两个表 TaskSchedule 和 TaskHost
        # 保存任务 到我们自己的定时任务数据表
        task_schedule_obj = models.TaskSchedule.objects.create(**{
            'period_beat': period_beat, # celery-beat的任务id值
            'period_way': period_way,
            'task_cmd': task_cmd,
            'period_content': period_content,
            'task_name': task_name,
            'period_status': '1' , # 默认为激活状态
        })

        # 保存任务关联到主机
        for host_id in hosts_ids:
            models.TaskHost.objects.create(**{
                'tasks_id': task_schedule_obj.id,
                'hosts_id': host_id,
            })

        return Response({'xxx': 'ooo'})
